import express, { Router } from 'express';
import { PrismaClient } from '@prisma/client';
import response from '../utils/response';
import { authenticateToken } from '../middleware/auth';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 提交联系表单（客户端用）
router.post('/submit', async (req, res): Promise<any> => {
  try {
    const { name, email, phone, subject, message, language } = req.body;

    // 验证必填字段
    if (!name || !email || !message) {
      return response.error(res, '请填写必填字段');
    }

    // 获取IP地址和User-Agent
    const ipAddress = req.ip || req.connection.remoteAddress;
    const userAgent = req.headers['user-agent'];

    const contact = await prisma.contactForm.create({
      data: {
        name,
        email,
        phone,
        subject,
        message,
        language: language || 'en',
        ipAddress,
        userAgent
      }
    });

    return response.success(res, {
      id: contact.id
    }, '提交成功，我们会尽快与您联系');
  } catch (error) {
    console.error('提交联系表单失败:', error);
    return response.error(res, '提交失败，请稍后重试');
  }
});

// 获取联系表单列表（管理端用）
router.get('/list', authenticateToken, async (req, res): Promise<any> => {
  try {
    const { status, page = '1', pageSize = '20', search } = req.query;

    const where: any = {};
    
    if (status) {
      where.status = status;
    }

    if (search) {
      where.OR = [
        { name: { contains: search as string } },
        { email: { contains: search as string } },
        { subject: { contains: search as string } },
        { message: { contains: search as string } }
      ];
    }

    const total = await prisma.contactForm.count({ where });

    const contacts = await prisma.contactForm.findMany({
      where,
      orderBy: { createdAt: 'desc' },
      skip: (parseInt(page as string) - 1) * parseInt(pageSize as string),
      take: parseInt(pageSize as string)
    });

    return response.success(res, {
      list: contacts,
      total,
      page: parseInt(page as string),
      pageSize: parseInt(pageSize as string)
    }, '获取联系表单列表成功');
  } catch (error) {
    console.error('获取联系表单列表失败:', error);
    return response.error(res, '获取联系表单列表失败');
  }
});

// 获取联系表单详情
router.get('/:id', authenticateToken, async (req, res): Promise<any> => {
  try {
    const { id } = req.params;

    const contact = await prisma.contactForm.findUnique({
      where: { id: parseInt(id) }
    });

    if (!contact) {
      return response.error(res, '联系表单不存在', 404);
    }

    // 如果是未读状态，自动标记为已读
    if (contact.status === 'unread') {
      await prisma.contactForm.update({
        where: { id: parseInt(id) },
        data: { status: 'read' }
      });
      contact.status = 'read';
    }

    return response.success(res, contact, '获取联系表单详情成功');
  } catch (error) {
    console.error('获取联系表单详情失败:', error);
    return response.error(res, '获取联系表单详情失败');
  }
});

// 更新联系表单状态
router.put('/:id/status', authenticateToken, async (req, res): Promise<any> => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    const validStatuses = ['unread', 'read', 'replied', 'archived'];
    if (!validStatuses.includes(status)) {
      return response.error(res, '无效的状态值');
    }

    const contact = await prisma.contactForm.update({
      where: { id: parseInt(id) },
      data: { status }
    });

    return response.success(res, contact, '更新状态成功');
  } catch (error) {
    console.error('更新联系表单状态失败:', error);
    return response.error(res, '更新状态失败');
  }
});

// 回复联系表单
router.post('/:id/reply', authenticateToken, async (req, res): Promise<any> => {
  try {
    const { id } = req.params;
    const { replyContent } = req.body;

    if (!replyContent) {
      return response.error(res, '请输入回复内容');
    }

    const contact = await prisma.contactForm.update({
      where: { id: parseInt(id) },
      data: {
        status: 'replied',
        replyContent,
        repliedAt: new Date()
      }
    });

    // TODO: 这里可以添加发送邮件的逻辑
    // await sendEmail(contact.email, replyContent);

    return response.success(res, contact, '回复成功');
  } catch (error) {
    console.error('回复联系表单失败:', error);
    return response.error(res, '回复失败');
  }
});

// 批量更新状态
router.put('/batch/status', authenticateToken, async (req, res): Promise<any> => {
  try {
    const { ids, status } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return response.error(res, '请选择要更新的表单');
    }

    const validStatuses = ['unread', 'read', 'replied', 'archived'];
    if (!validStatuses.includes(status)) {
      return response.error(res, '无效的状态值');
    }

    const result = await prisma.contactForm.updateMany({
      where: {
        id: {
          in: ids.map(id => parseInt(id))
        }
      },
      data: { status }
    });

    return response.success(res, result, `成功更新 ${result.count} 条记录`);
  } catch (error) {
    console.error('批量更新状态失败:', error);
    return response.error(res, '批量更新失败');
  }
});

// 删除联系表单
router.delete('/:id', authenticateToken, async (req, res): Promise<any> => {
  try {
    const { id } = req.params;

    await prisma.contactForm.delete({
      where: { id: parseInt(id) }
    });

    return response.success(res, null, '删除成功');
  } catch (error) {
    console.error('删除联系表单失败:', error);
    return response.error(res, '删除失败');
  }
});

// 批量删除
router.delete('/batch/delete', authenticateToken, async (req, res): Promise<any> => {
  try {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return response.error(res, '请选择要删除的表单');
    }

    const result = await prisma.contactForm.deleteMany({
      where: {
        id: {
          in: ids.map(id => parseInt(id))
        }
      }
    });

    return response.success(res, result, `成功删除 ${result.count} 条记录`);
  } catch (error) {
    console.error('批量删除失败:', error);
    return response.error(res, '批量删除失败');
  }
});

// 获取统计数据
router.get('/stats/overview', authenticateToken, async (req, res): Promise<any> => {
  try {
    const [total, unread, read, replied, archived] = await Promise.all([
      prisma.contactForm.count(),
      prisma.contactForm.count({ where: { status: 'unread' } }),
      prisma.contactForm.count({ where: { status: 'read' } }),
      prisma.contactForm.count({ where: { status: 'replied' } }),
      prisma.contactForm.count({ where: { status: 'archived' } })
    ]);

    // 获取最近7天的提交趋势
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    const recentSubmissions = await prisma.contactForm.groupBy({
      by: ['createdAt'],
      where: {
        createdAt: {
          gte: sevenDaysAgo
        }
      },
      _count: true
    });

    return response.success(res, {
      total,
      unread,
      read,
      replied,
      archived,
      recentSubmissions
    }, '获取统计数据成功');
  } catch (error) {
    console.error('获取统计数据失败:', error);
    return response.error(res, '获取统计数据失败');
  }
});

export default router;